import { reactive, shallowRef } from 'vue'
import { baseWSURL } from '../api/ws'
import { useChart } from './useChart'
import { useTotalFlow } from './useTotalFlow'
const { playAlarmAudio } = useChart()
const { currentPipelineId } = useTotalFlow()

const socket = shallowRef()
const lightMap = new Map() // 存储各个管线所对应的指示灯的class

function openSocket() {
  const user = JSON.parse(localStorage.getItem('user'))
  const socketUrl = `${baseWSURL}/status/${user.id}`
  if (!socket.value) {
    socket.value = new WebSocket(socketUrl, [localStorage.getItem('token')])
  }
  socket.value.onopen = function () {
    console.log('状态websocket已打开')
  }
  socket.value.onmessage = (msg) => {
    const data = JSON.parse(msg.data)
    if (data.type === 'status') {
      const light = lightMap.get(data.realData.pipelineId)
      if (light) {
        if (data.realData.value !== -1) {
          light.danger = true
          if (currentPipelineId.value !== data.realData.pipelineId) {
            playAlarmAudio()
          }
        } else {
          light.danger = false
        }
      }
    }
  }
  socket.value.onclose = function () {
    console.log('状态websocket已关闭')
  }
  socket.value.onerror = function () {
    closeSocket()
    console.log('状态websocket发生了错误')
  }
}
function closeSocket() {
  if (socket.value) {
    socket.value.close()
    socket.value = null
  }
}
function getLightClass(item) {
  if (lightMap.has(item.id)) {
    return lightMap.get(item.id)
  }
  const light = reactive({
    circle: true,
    danger: false,
    health: !item.disabled,
    disable: item.disabled
  })
  lightMap.set(item.id, light)
  return light
}

export const useStatus = () => {
  return {
    lightMap,
    openSocket,
    closeSocket,
    getLightClass
  }
}
